import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
import { ADD_TODO,OPEN_BAR, COMPLETE_TODO, SET_VISIBILITY_FILTER, VisibilityFilters} from '../actions'
import {SELECT_SUBREDDIT, INVALIDATE_SUBREDDIT ,
    REQUEST_POSTS, RECEIVE_POSTS} from '../actions/asyn'
const { SHOW_ALL } = VisibilityFilters;

function visibilityFilter(state = SHOW_ALL, action) {//在这里赋值了一个SHOW_ALL  TM的
    switch (action.type) {
        case SET_VISIBILITY_FILTER:
            return action.filter;
        default:
            return state
    }
}
//showtime
function showLeftBar(state=false,action) {
    switch (action.type){
        case OPEN_BAR:
            return action.openState;
        default:
            return state;
    }

}
function selectedSubreddit(state = 'reactjs', action) {
    switch (action.type) {
        case SELECT_SUBREDDIT:
            return action.subreddit;
        default:
            return state
    }
}


function posts(state = {
    isFetching: false,
    didInvalidate: false,
    items: []
}, action) {
    switch (action.type) {
        case INVALIDATE_SUBREDDIT:
            return {
                ...state,didInvalidate: true
            };
        case REQUEST_POSTS:
            return{...state,isFetching: true, didInvalidate: false};
        case RECEIVE_POSTS:
            return {...state,isFetching: false,
                didInvalidate: false,
                items: action.posts,
                lastUpdated: action.receivedAt};
        default:
            return state
    }
}

function postsBySubreddit(state = {}, action) {
    switch (action.type) {
        case INVALIDATE_SUBREDDIT:
        case RECEIVE_POSTS:
        case REQUEST_POSTS:
            return{
                ...state,[action.subreddit]: posts(state[action.subreddit], action)
            };
        /*let nextState = {}
         nextState[action.subreddit] = posts(state[action.subreddit], action)
         return Object.assign({}, state, nextState)与上面三行等价*/
        default:
            return state
    }
}
function todos(state = [], action) {
    switch (action.type) {
        case ADD_TODO:
            return [
                ...state,
                {
                    text: action.text,
                    completed: false
                }
            ]
        case COMPLETE_TODO:
            return [
                ...state.slice(0, action.index),
                {...state[action.index],completed: true},
                ...state.slice(action.index + 1)
            ]
        default:
            return state
    }
}
const todoApp = combineReducers({
    visibilityFilter,
    todos,
    showLeftBar,
    postsBySubreddit,
    selectedSubreddit,
    routing:routerReducer
});
export default todoApp